package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.mapper.*;
import com.tanhua.server.pojo.Answers;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Question;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TestSoulService {
    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SoulAnswerMapper soulAnswerMapper;
    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulMapper soulMapper;

    @Autowired
    private ConclusionMapper conclusionMapper;

    /**
     * 查询结果
     *
     * @param reportId 报告id
     * @return 结果对象集
     */
    public ReportResultVo testResult(Long reportId) {
        //获取User对象
        User User = UserThreadLocal.get();
        //定义返回结果VO对象
        ReportResultVo reportResultVo = new ReportResultVo();
        // 查询报告结果
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("report_id", reportId);
        Report report = this.reportMapper.selectOne(queryWrapper);
        if (report == null) {
            // 说明该用户还没有生成报告
            return null;
        }
        //给报告对象赋值
        reportResultVo.setConclusion(report.getConclusion());
        reportResultVo.setCover(report.getCover());

        //给维度属性赋值
        List<Dimensions> dimensions = new ArrayList<>();
        Double extroversion = report.getExtroversion();     // 外向维度值
        Double judge = report.getJudge();                   // 判断维度值
        Double reason = report.getReason();                 // 理性维度值
        Double abstracts = report.getAbstracts();           // 抽象纬度值

        dimensions.add(new Dimensions("extroversion", String.valueOf(extroversion)));
        dimensions.add(new Dimensions("judge", String.valueOf(judge)));
        dimensions.add(new Dimensions("reason", String.valueOf(reason)));
        dimensions.add(new Dimensions("abstracts", String.valueOf(abstracts)));

        reportResultVo.setDimensions(dimensions);


        List<SimilarYou> similarYouList = new ArrayList<>();
        // 查询缘分值
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(User.getId(), 1, 10);
        if (pageInfo != null) {
            List<RecommendUser> records = pageInfo.getRecords();
            if (!CollectionUtils.isEmpty(records)) {
                for (RecommendUser record : records) {
                    SimilarYou similarYou = new SimilarYou();
                    UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(record.getToUserId());
                    if (userInfo == null) {
                        continue;
                    }
                    similarYou.setId(userInfo.getUserId());
                    similarYou.setAvatar(userInfo.getLogo());
                    similarYouList.add(similarYou);
                }
            }
            reportResultVo.setSimilarYou(similarYouList);
        }
        return reportResultVo;
    }


    public List<Soul1Vo> QuestionnaireList() {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        List<Soul1Vo> soul1Vos = new ArrayList<>();
        QueryWrapper<Soul> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("questionnaire_id");
        List<Soul> soulList = soulMapper.selectList(queryWrapper);
        for (Soul soul : soulList) {
            Integer questionnaireId = soul.getQuestionnaireId();
            Soul1Vo soul1Vo = new Soul1Vo(String.valueOf(questionnaireId), soul.getName(), soul.getCover(), soul.getLevel(), soul.getStar());
            if (questionnaireId == 1) {
                soul1Vo.setIsLock(0);
            } else {
                String reportId = getReportId(questionnaireId - 1, userId);
                if (null == reportId) {
                    soul1Vo.setIsLock(1);
                } else {
                    soul1Vo.setIsLock(0);
                }
            }
            String reportId = getReportId(questionnaireId, userId);
            soul1Vo.setReportId(reportId);
            List<Question> questions = getQuestionsAndOptions(questionnaireId);
            soul1Vo.setQuestions(questions);

            soul1Vos.add(soul1Vo);
        }
        return soul1Vos;
    }

    private String getReportId(int questionnaireId, long userId) {
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("questionnaire_id", questionnaireId);
        queryWrapper.orderByAsc("updated");
        List<Report> reportList = reportMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(reportList)) {
            return null;
        }
        return String.valueOf(reportList.get(0).getReportId());
    }

    private List<SoulQuestion> getQuestions(int questionnaireId) {
        QueryWrapper<SoulQuestion> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id", questionnaireId);
        List<SoulQuestion> soulQuestions = soulQuestionMapper.selectList(queryWrapper);
        return soulQuestions;
    }

    private List<Question> getQuestionsAndOptions(int questionnaireId) {
        List<SoulQuestion> questions = getQuestions(questionnaireId);
        List<Question> questionList = new ArrayList<>();
        for (SoulQuestion question : questions) {
            Integer questionId = question.getQuestionId();
            QueryWrapper<SoulAnswer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("question_id", questionId);
            List<SoulAnswer> soulAnswers = soulAnswerMapper.selectList(queryWrapper);
            List<Option> options = new ArrayList<>();
            for (SoulAnswer soulAnswer : soulAnswers) {
                Option option1 = new Option(String.valueOf(soulAnswer.getAnswerId()), soulAnswer.getContent());
                options.add(option1);
            }
            Question question1 = new Question(String.valueOf(questionId), question.getContent(), options);

            questionList.add(question1);
        }
        return questionList;
    }


    public String submitQuestionnaire(List<Answers> answersList) {
        User user = UserThreadLocal.get();

        Long userId = user.getId();
        int score = 0;
        int QuestionaireId = 0;

        for (Answers answers : answersList) {

            QueryWrapper<SoulAnswer> query = new QueryWrapper<>();
            query.eq("question_id", answers.getQuestionId());
            query.eq("answerId", answers.getOptionId());
            query.select("score");
            SoulAnswer soulAnswer = this.soulAnswerMapper.selectOne(query);
            score += soulAnswer.getScore();

            QueryWrapper<SoulQuestion> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("question_id", answers.getQuestionId());
            queryWrapper.select("questionnaire_id");
            SoulQuestion soulQuestion = this.soulQuestionMapper.selectOne(queryWrapper);
            QuestionaireId = soulQuestion.getQuestionnaireId();
        }

        QueryWrapper<Conclusion> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("min_score",score);
        queryWrapper.ge("max_score",score);
        Conclusion conclusion = conclusionMapper.selectOne(queryWrapper);

        Report report = new Report();
        report.setUserId(userId);                                   //用户Id
        report.setQuestionnaireId(QuestionaireId);                  //问卷Id
        report.setReportId(userId + QuestionaireId);                //报表ID
        report.setCover(conclusion.getCover());                     //封面
        report.setConclusion(conclusion.getConclusion());           //鉴定结果
        report.setExtroversion(25D);                                //外向
        report.setJudge(25D);                                       //判断
        report.setAbstracts(25D);                                   //抽象
        report.setReason(25D);                                      //理性

        this.reportMapper.insert(report);

        return String.valueOf(report.getReportId());
    }

}
